Argparse Optional Boolean Arguments

Creating optional arguments in argparse that are booleans

Created: July 8th 2019
Updated: December 7th 2019
Connect with us on
image
image

Argparse is a well known library for writing highly extensible, and robust scripts. In this demo you will learn how to set up an optional boolean argument.

Definitions

Some terms to help you navigate the post

argparse

A module that allows you to create robust scripts and handles much of the complexity of this in the backend. See full python reference for the module for details

Arguments

Arguments are special characters you specify when running a script that allow you to alter the default functionality, provide additional information, or ask the script to print information about itself such as version or help text. Most scripts include a -h or --help option to address the second example, and to get this information you would type python <script file> -h or python <script file> --help

Usage

In this repo you can see the demo code and actually run it by running python optional_boolean_arguments.py or python3 optional_boolean_arguments.py

Real World Applications

Lets say you are building a script that gives you the information about a domain. One optional argument could be -e or --expiry when this option is used the script returns the SSL and domain expiry information.

Files

optional_boolean_arguments_demo.py

"""A demo of optional boolean arguments using argparse."""
import argparse # Module used to set up argument parser

# Setting up Main Argument Parser
main_parser = argparse.ArgumentParser(description="A demo of optional boolean arguments")

# Adding optional boolean argument
main_parser.add_argument("-r", '--run',
    help="If argument is present run 'print('hello')'",
    action='store_true', # If -r is present, the argument is True
    default=False, # If -r is not present the argument is False
    required=False, # Makes argument optional
    dest="run"
) # Makes variable accessible as 'run', see lines 19-26

def function_to_run():
    """Function intended to run if the -r or --run command is used"""
    print("-r or --run was called")
    # Argument parsing
    args = main_parser.parse_args()
    if args.run: # If -r or --run is specified, run function_to_run()
        function_to_run()
    else: 
        # If -r or --run was not present
        print("-r or --run was not called")

Thank you for your support!

Be sure to share the post if it was helpful!